<template>
  <div class="app-container">
    <div :flex="`main:${activeTable === 2 ? 'right':'justify'}`">
      <el-form v-if="activeTable !== 2" :inline="true">
        <el-form-item label="表名称">
          <el-input
            v-model="queryParams.groupname"
            placeholder="请输入表名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="部门状态" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >搜索</el-button>
          <el-button
            v-hasPermi="['system:dept:add']"
            class="filter-item"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" size="mini" :plain="activeTable !== 0" @click="handleTabClick(0)">系统表维护</el-button>
        <el-button type="primary" size="mini" :plain="activeTable !== 3" @click="handleTabClick(3)">系统列表</el-button>
        <el-button type="primary" size="mini" :plain="activeTable !== 1" @click="handleTabClick(1)">码表维护</el-button>
        <el-button type="primary" size="mini" :plain="activeTable !== 2" @click="handleTabClick(2)">分组维护</el-button>
      </div>
    </div>

    <el-row :gutter="10" class="margin_bottom_8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:edit']"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate(undefined)"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:remove']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
    </el-row>

    <el-table v-if="activeTable === 0" key="a" v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="表名" align="center" prop="tablename" />
      <el-table-column label="表别名" align="center" prop="ailas" />
      <el-table-column label="库名" align="center" prop="dbname" />
      <el-table-column label="类型" align="center" prop="type" />
      <el-table-column label="创建人" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="time" :formatter="row=>formatDate(row.time)" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:post:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:post:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-table v-else-if="activeTable === 3" key="b" v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="列名" align="center" prop="colname" />
      <el-table-column label="列别名" align="center" prop="ailas" />
      <el-table-column label="是否可见" align="center" prop="isshow" />
      <el-table-column label="是否转义" align="center" prop="iscode" />
      <el-table-column label="是否可查" align="center" prop="isCanQuery" />
      <el-table-column label="码表ID" align="center" prop="codeid" />
      <el-table-column label="列宽" align="center" prop="width" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:post:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:post:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-table v-else-if="activeTable === 1" key="c" v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="码值名称" align="center" prop="codename" />
      <el-table-column label="码值" align="center" prop="codevalue" />
      <el-table-column label="码值别名" align="center" prop="codealias" />
      <el-table-column label="码值类型" align="center" prop="codetype" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:post:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:post:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-table
      v-else
      key="d"
      v-loading="loading"
      :data="tableList"
      row-key="groupname"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="groupname" label="分组名称" />
      <el-table-column prop="id" label="系统序号" />
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermi="['system:dept:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['system:dept:add']" size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button v-if="scope.row.pid != 0" v-hasPermi="['system:dept:remove']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-button slot="empty" type="primary" icon="el-icon-plus" @click="handleAdd()" />
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px">

      <el-form v-if="activeTable === 0" ref="form" key="systableForm" :model="form" label-width="80px">
        <el-form-item label="表名" prop="tablename" required>
          <el-input v-model="form.tablename" placeholder="请输入表名" />
        </el-form-item>
        <el-form-item label="表别名" prop="ailas" required>
          <el-input v-model="form.ailas" placeholder="请输入表别名" />
        </el-form-item>
        <el-form-item label="类型" prop="type" required>
          <el-input-number v-model="form.type" placeholder="请输入类型" />
        </el-form-item>
        <el-form-item label="数据库" prop="dbname" required>
          <el-input v-model="form.dbname" placeholder="数据库" />
        </el-form-item>
      </el-form>
      <el-form v-if="activeTable === 3" ref="form" key="syscolumForm" :model="form" label-width="80px">
        <el-form-item label="列名" prop="colname" required>
          <el-input v-model="form.colname" placeholder="请输入表名" />
        </el-form-item>
        <el-form-item label="列别名" prop="ailas" required>
          <el-input v-model="form.ailas" placeholder="请输入表别名" />
        </el-form-item>
        <el-form-item label="是否可见" prop="isshow" required>
          <el-switch v-model="form.isshow" style="width:185px" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="是否转义" prop="iscode" required>
          <el-switch v-model="form.iscode" style="width:185px" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="是否可查" prop="isCanQuery" required>
          <el-switch v-model="form.isCanQuery" style="width:185px" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="码表ID" prop="codeid" required>
          <el-input-number v-model="form.codeid" placeholder="码表ID" />
        </el-form-item>
        <el-form-item label="列宽" prop="width" required>
          <el-input-number v-model="form.width" placeholder="列宽" />
        </el-form-item>
      </el-form>
      <el-form v-else-if="activeTable === 1" ref="form" key="codeForm" :model="form" label-width="80px">
        <el-form-item label="码值名称" prop="codename" required>
          <el-input v-model="form.codename" placeholder="码值名称" />
        </el-form-item>
        <el-form-item label="码值" prop="codevalue" required>
          <el-input v-model="form.codevalue" placeholder="码值" />
        </el-form-item>
        <el-form-item label="码值别名" prop="codealias" required>
          <el-input v-model="form.codealias" placeholder="码值别名" />
        </el-form-item>
        <el-form-item label="码值类型" prop="codetype" required>
          <el-input-number v-model="form.codetype" placeholder="码值类型" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" required>
          <el-input v-model="form.remark" placeholder="备注" />
        </el-form-item>
      </el-form>
      <el-form v-else-if="activeTable === 2" ref="form" key="groupForm" :model="form" label-width="80px">
        <el-row>
          <el-col v-if="form.pid !== 0" :span="24">
            <el-form-item label="上级分组" prop="pid">
              <treeselect v-model="form.pid" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级分组" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分组名称" prop="groupname">
              <el-input v-model="form.groupname" placeholder="请输入分组名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryList as listSystem, addUpdateItem as addUpdateSystem, deleteById as delSystem } from '@/api/setting/systable'
import { queryList as listCode, addUpdateItem as addCode, deleteById as delCode } from '@/api/setting/code'
import { queryListAll as listGroup, addUpdateItem as addGroup, deleteById as delGroup } from '@/api/setting/group'
import { queryList as listColum, addUpdateItem as addColum, deleteById as delColum } from '@/api/setting/syscolum'
import { mapGetters } from 'vuex'
// import { listPlan, delPlan, addPlan, updatePlan, exportPlan } from '@/api/setting/plan'
// import { listSyscolum } from '@/api/setting/table'
// import { listUser } from '@/api/system/user'
import { formatDate } from '@/utils'
// import { listPath, getPath, addPathCamera, delPath, addPath, updatePath, exportPath } from '@/api/setting/path'
import Treeselect from '@riophae/vue-treeselect'
// import { treeselect } from '@/api/system/dept'

export default {
  name: 'System',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 路径表格数据
      // 表格树数据
      tableList: [],
      // 表格树数据
      systemList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        groupname: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      activeTable: 0,
      userList: []
    }
  },
  computed: {
    funObj() {
      return [
        { list: listSystem, add: addUpdateSystem, update: addUpdateSystem, del: delSystem },
        { list: listCode, add: addCode, update: addCode, del: delCode },
        { list: listGroup, add: addGroup, update: addGroup, del: delGroup },
        { list: listColum, add: addColum, update: addColum, del: delColum }
      ]
    },
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    formatDate,
    // getUsrList({ id }) {
    //   listUser({ deptId: id }).then(res => {
    //     this.userList = res.rows
    //   })
    // },
    handleTabClick(tab) {
      this.activeTable = tab
      this.getList()
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true
      this.funObj[this.activeTable]['list'](this.queryParams).then(response => {
        this.tableList = this.activeTable === 2 ? this.handleTree(response.data, 'id', 'pid') : response.data
        this.loading = false
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this._row = selection[0]
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.groupname,
        children: node.children
      }
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listGroup().then(response => {
        this.deptOptions = this.handleTree(response.data, 'id', 'pid')
      })
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        pid: undefined,
        groupname: undefined
        // orderNum: undefined,
        // leader: undefined,
        // phone: undefined,
        // email: undefined,
        // status: '0'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row !== undefined) {
        this.form.pid = row.id
      } else {
        this.form.pid = 0
      }
      this.open = true
      this.title = '添加系统注册表'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      // getSystem(row.id).then(response => {
      //   this.form = response.data
      //   this.open = true
      //   this.title = '修改系统注册表'
      // })

      this.form = JSON.parse(JSON.stringify(row || this._row))
      // Object.assign(this.form, row)
      this.open = true
      this.title = '修改部门'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id) {
            this.funObj[this.activeTable]['update']({ creater: this.userId, ...this.form }).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            this.funObj[this.activeTable]['add']({ creater: this.userId, ...this.form }).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.groupname + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return this.funObj[this.activeTable]['del'](row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {})
    }
  }
}
</script>
